@page "/k8s/deploy/list"
@using FOPS.Abstract.K8S.Entity
@using FOPS.Abstract.K8S.Enum
@using FOPS.Abstract.K8S.Server
@using FOPS.Abstract.MetaInfo.Entity
@using FOPS.Abstract.MetaInfo.Server
@using FS.Extends
@inject IIocManager _iocManager;
@inject NavigationManager nav;
@inject IJSRuntime js;

<div class="layui-card">
    <div class="layui-card-header" id="anchor-play-header">
        模板发布
        <select style="display:inline;width: 200px;" @onchange="GroupChange">
            <option value="0">全部</option>
            @foreach (var clusterVO in _lstGroup)
            {
                <option value="@clusterVO.Id">@clusterVO.Name</option>
            }
        </select>
        
        <select style="display:inline;width: 200px;" @onchange="ClusterChange">
            @foreach (var clusterVO in _lstCluster)
            {
                <option value="@clusterVO.Id">@clusterVO.Name - @clusterVO.RuntimeEnvType</option>
            }
        </select>
        <div class="layui-right">
            <button class="layui-btn layui-btn-danger" @onclick="DeployAsync"><i class="am-icon-plus"></i> 全部发布</button>
        </div>
    </div>
    <div class="layui-card-body">
        <div class="layui-form layui-border-box layui-table-view" lay-filter="LAY-table-1" style="">
            <div class="layui-table-box">
                <div class="layui-table-header">
                    <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                        <thead>
                        <tr>
                            <th data-field="ID">
                                <div class="layui-table-cell laytable-cell-14-0-0">
                                    <span>ID</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-1">
                                    <span>项目名称</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-2">
                                    <span>Deployment模板</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-2">
                                    <span>Service模板</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-2">
                                    <span>Ingress模板</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-2">
                                    <span>Config模板</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-3">
                                    <span>操作</span>
                                </div>
                            </th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <div class="layui-table-body layui-table-main">
                    <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                        <tbody>
                        @for (var index = 0; index < _lst.Count; index++)
                        {
                            var info = _lst[index];
                            <tr data-index="@index">
                                <td>
                                    <div class="layui-table-cell laytable-cell-14-0-0"> @info.Id</div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-1">
                                        @info.Name
                                    </div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-2">
                                        <select @bind="info.K8STplDeployment" style="display:block;">
                                            <option value="0">不需要</option>
                                            @foreach (var yamlTplVO in _lstTpl.FindAll(O => O.K8SKindType == EumK8SKind.Deployment))
                                            {
                                                <option value="@yamlTplVO.Id">@yamlTplVO.Name</option>
                                            }
                                        </select>
                                    </div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-2">
                                        <select @bind="info.K8STplService" style="display:block;">
                                            <option value="0">不需要</option>
                                            @foreach (var yamlTplVO in _lstTpl.FindAll(O => O.K8SKindType == EumK8SKind.Service))
                                            {
                                                <option value="@yamlTplVO.Id">@yamlTplVO.Name</option>
                                            }
                                        </select>
                                    </div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-2">
                                        <select @bind="info.K8STplIngress" style="display:block;">
                                            <option value="0">不需要</option>
                                            @foreach (var yamlTplVO in _lstTpl.FindAll(O => O.K8SKindType == EumK8SKind.Ingress))
                                            {
                                                <option value="@yamlTplVO.Id">@yamlTplVO.Name</option>
                                            }
                                        </select>
                                    </div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-2">
                                        <select @bind="info.K8STplConfig" style="display:block;">
                                            <option value="0">不需要</option>
                                            @foreach (var yamlTplVO in _lstTpl.FindAll(O => O.K8SKindType == EumK8SKind.Config))
                                            {
                                                <option value="@yamlTplVO.Id">@yamlTplVO.Name</option>
                                            }
                                        </select>
                                    </div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-3">
                                        <button class="layui-btn layui-btn-sm" @onclick="() => Save(info.Id)">保存</button>
                                        <button class="layui-btn layui-btn-sm layui-btn-danger" @onclick="() => DeployAsync(info.Id)">发布</button>
                                    </div>
                                </td>
                            </tr>
                        }
                        </tbody>
                    </table>
                </div>
            </div>
            <PageSplit PageIndex="1" PageSize="@_pageSize" TotalCount="@_totalCount" PageUrl="/k8s/deploy/list/{index}"></PageSplit>
        </div>
    </div>
</div>
<style>
    .laytable-cell-14-0-0{ width: 80px; }
    .laytable-cell-14-0-1{ width: 150px; }
    .laytable-cell-14-0-2{ width: 180px; }
    .laytable-cell-14-0-3{ width: 150px; }
    select { width: 150px; }
</style>

@code{

    private int _totalCount;
    private int _pageSize = 999;
    private int _groupId;

    private int _clusterId;
    private List<ProjectGroupVO> _lstGroup = new();
    private List<ProjectVO> _lst = new();
    private List<YamlTplVO> _lstTpl = new();
    private List<ClusterVO> _lstCluster = new();
    private bool _isFirst;

    protected override async Task OnInitializedAsync()
    {
        if (_isFirst) return;
        _isFirst = true;

        _lstGroup = await _iocManager.Resolve<IProjectGroupService>().ToListAsync()??new();
        // 模板
        _lstTpl = await _iocManager.Resolve<IYamlTplService>().ToListAsync()??new();
        _lstTpl = _lstTpl.OrderByDescending(o => o.Id).ToList();

        // 集群
        _lstCluster = await _iocManager.Resolve<IClusterService>().ToListAsync()??new();
        if (_lstCluster.Count > 0) _clusterId = _lstCluster[0].Id;
        
        await GetList();
    }

    private async Task Save(int id)
    {
        var projectVO = _lst.Find(o => o.Id == id);
        await _iocManager.Resolve<IProjectService>().UpdateAsync(id, projectVO);
        await js.InvokeVoidAsync("layer.msg", "保存成功", new {icon = 1});
    }

    private async Task GroupChange(ChangeEventArgs args)
    {
        _groupId = args.Value.ConvertType(0);
        await GetList();
    }

    private async Task DeployAsync()
    {
        var load = await js.InvokeAsync<int>("layer.load", 0, "{shade: false}");
        var clusterVO = _lstCluster.Find(o => o.Id == _clusterId);
        if (clusterVO == null)
        {
            await js.InvokeVoidAsync("layer.alert", "请先选择集群环境", new {icon = 0});
            return;
        }

        var deployService = _iocManager.Resolve<IDeployService>();
        try
        {
            var runShellResult = await deployService.DeployAsync(_lst, clusterVO, _lstTpl);
            if (runShellResult.IsError) await js.InvokeVoidAsync("layer.alert", runShellResult.OutputBr, new {icon = 2, title = "出错了"});
            else await js.InvokeVoidAsync("layer.msg", runShellResult.OutputBr, new {icon = 1, title = "执行结果"});
        }
        catch (Exception e)
        {
            await js.InvokeVoidAsync("layer.alert", e.Message, new {icon = 2, title = "出错了"});
        }
        await js.InvokeVoidAsync("layer.close", load);
    }

    private async Task DeployAsync(int id)
    {
        var load = await js.InvokeAsync<int>("layer.load", 0, "{shade: false}");
        var clusterVO = _lstCluster.Find(o => o.Id == _clusterId);
        if (clusterVO == null)
        {
            await js.InvokeVoidAsync("layer.close", load);
            await js.InvokeVoidAsync("layer.alert", "请先选择集群环境", new {icon = 0});
            return;
        }

        var projectVO = _lst.Find(o => o.Id == id);
        if (projectVO == null)
        {
            await js.InvokeVoidAsync("layer.close", load);
            await js.InvokeVoidAsync("layer.alert", "项目不存在", new {icon = 0});
            return;
        }

        var deployService = _iocManager.Resolve<IDeployService>();
        try
        {
            var runShellResult = await deployService.DeployAsync(projectVO, clusterVO, _lstTpl);
            if (runShellResult.IsError) await js.InvokeVoidAsync("layer.alert", runShellResult.OutputBr, new {icon = 2, title = "出错了"});
            else await js.InvokeVoidAsync("layer.msg", runShellResult.OutputBr, new {icon = 1, title = "执行结果"});
        }
        catch (Exception e)
        {
            await js.InvokeVoidAsync("layer.alert", e.Message, new {icon = 2, title = "出错了"});
        }
        await js.InvokeVoidAsync("layer.close", load);
    }

    private async Task ClusterChange(ChangeEventArgs args)
    {
        _clusterId = args.Value.ConvertType(0);
        await GetList();
    }

    private async Task GetList()
    {
        // 重新读取所有项目列表
        _lst = await _iocManager.Resolve<IProjectService>().ToListAsync()??new();
    
        // 如果项目组不包含当前选中的组，则移除项目
        if (_groupId > 0)
        {
            _lst.RemoveAll(o => o.GroupId != _groupId);
        }
        
        // 遍历项目组ID
        var projectGroupIds = _lst.Select(o => o.GroupId).ToList()??new();
        for (var i = 0; i < projectGroupIds.Count; i++)
        {
            var projectGroupId = projectGroupIds[i];
            var info = await _iocManager.Resolve<IProjectGroupService>().ToInfoAsync(projectGroupId);
            
            // 如果项目组不包含当前选中的集群，则移除项目
            if (!info.ClusterIds.Contains(_clusterId))
                _lst.RemoveAll(o => o.GroupId == projectGroupId);
        }

        _lst        = _lst.OrderByDescending(o => o.Id).ToList();
        _totalCount = _lst.Count;
    }

}